package com.xw.service.sysconfig;

import cn.hutool.crypto.SecureUtil;
import com.google.common.collect.Maps;
import com.xw.common.Const;
import com.xw.dao.*;
import com.xw.model.*;
import com.xw.service.common.impl.BaseServiceImpl;
import com.xw.util.AppUtil;
import com.xw.util.JsonData;
import com.xw.vo.UserInfoVo;
import com.xw.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wangxiaoxiao
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private SysUserInfoMapper userInfoMapper;
    @Resource
    private VerificationCodeService codeService;
    @Resource
    private SysVerificationCodeMapper codeMapper;
    @Resource
    private WithdrawMapper withdrawMapper;
    @Resource
    private VideosMapper videosMapper;
    @Resource
    private VideosItemMapper videosItemMapper;


    @Override
    public Map<String, Object> loginByWX(String userPhone, String userNickName, String userImg) {
        Map map = Maps.newHashMap();
        User model = new User();
        model.setUserPhone(userPhone);
        User user = userMapper.selectOne(model);
        if (user != null){
            //登录成功,判断状态
            if (user.getUserStatus() == 2){
                return JsonData.fail("您的账户已被禁用，请联系管理员");
            }
            //查询userInfo
            UserInfo info = new UserInfo();
            info.setUserId(user.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(info);
            map.put("user",user);
            map.put("userInfo",userInfo);
        }else{
            //用户不存在
            model = new User();
            model.setUserPhone(userPhone);
            User one = userMapper.selectOne(model);
            if (one != null){
                //查询userInfo
                UserInfo info = new UserInfo();
                info.setUserId(one.getUserId());
                UserInfo userInfo = userInfoMapper.selectOne(info);
                map.put("user",one);
                map.put("userInfo",userInfo);
            }else{
                //没有注册，就直接注册
                user = new User();
                String userId = AppUtil.uuid();
                user.setUserId(userId);
                user.setUserPhone(userPhone);
                //默认密码
                user.setUserPwd("");
                user.setUserType(1);
                user.setUserLoginName(userPhone);
                //微信昵称
                if (StringUtils.isNotBlank(userNickName)){
                    user.setUserNickName(userNickName);
                }
                if (StringUtils.isNotBlank(userImg)){
                    user.setUserImg(userImg);
                }
                user.setUserStatus(1);
                user.setBalance(0.0);
                user.setUserToken(AppUtil.uuid());
                user.setCreateTime(new Date());
                UserInfo info = new UserInfo();
                info.setUserId(userId);
                info.setUiId(AppUtil.uuid());
                userMapper.insertSelective(user);
                userInfoMapper.insertSelective(info);
                map.put("user",user);
                map.put("userInfo",info);

            }
        }


        return JsonData.success(map);
    }

    /**
     * @需求描述:余额提现业务逻辑层
     * @创建人:whh
     * @创建时间: 2019/11/23
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map cashOutBalance(String userId, Double newBalance, Double oldCashOut) {
        User user =  userMapper.selectByPrimaryKey(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(userId);
        List<UserInfo> userInfo = userInfoMapper.select(userInfoVo);
        if (null != user){
            user.setBalance(newBalance);
            Integer result = userMapper.updateByPrimaryKey(user);
            if (1 == result){

                Withdraw withdraw = new Withdraw();
                withdraw.setUserId(user.getUserId());
                withdraw.setMoney(oldCashOut);
                withdraw.setRealName(userInfo.get(0).getRealName());
                withdraw.setWithdrawType(3);
                withdraw.setWithdrawStatus(1);
                withdraw.setCreateTime(new Date());
                withdraw.setId(AppUtil.uuid());
                withdrawMapper.insertSelective(withdraw);
                return  JsonData.success(result,Const.OPREATE_MSG_SUCCESS);
            }
        }
        return JsonData.fail(Const.OPREATE_MSG_ERROR);
    }

    @Override
    public Map<String, Object> updateGenderByUiId(String uiId, Integer gender) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUiId(uiId);
        userInfo.setGender(gender);
        int i = userInfoMapper.updateByPrimaryKeySelective(userInfo);
        return JsonData.returnMap(i);
    }

    @Override
    public Map<String, Object> updateUserByUserId(String userId, String userImg, String userNickName) {
        //验证是否拉黑
        if (!StringUtils.equals("-1",userId) && StringUtils.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(userId);
            if (user.getUserStatus() == 2) {
                return JsonData.returnMap(811, "您的账号已被锁定");
            }
        }

        User user = new User();
        user.setUserId(userId);
        if (StringUtils.isNotBlank(userImg)){
            user.setUserImg(userImg);
        }
        if (StringUtils.isNotBlank(userNickName)){
            user.setUserNickName(userNickName);
        }
        int i = userMapper.updateByPrimaryKeySelective(user);

        return JsonData.returnMap(i);
    }

    @Override
    public Map removeJoinBlack(String userId) {
        User user = new User();
        user.setUserId(userId);
        user.setUserStatus(1);
        int i = userMapper.updateByPrimaryKeySelective(user);
        return JsonData.returnMap(i);
    }

    @Override
    public Map joinBlack(String userId) {
        User user = new User();
        user.setUserId(userId);
        user.setUserStatus(2);
        int i = userMapper.updateByPrimaryKeySelective(user);
        return JsonData.returnMap(i);
    }

    @Override
    public Map<String, Object> findUserByUserId(String userId) {
        //验证是否拉黑
        if (!StringUtils.equals("-1",userId) && StringUtils.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(userId);
            if (user.getUserStatus() == 2) {
                return JsonData.returnMap(811, "您的账号已被锁定");
            }
        }
        Map map = Maps.newHashMap();
        User user = userMapper.selectByPrimaryKey(userId);

        UserInfo info = new UserInfo();
        info.setUserId(userId);
        UserInfo userInfo = userInfoMapper.selectOne(info);

        map.put("user",user);
        map.put("userInfo",userInfo);
        return JsonData.success(map);
    }

    @Override
    public Map<String, Object> loginByPwd(String phone, String pwd) {
        Map map = Maps.newHashMap();

        User model = new User();
        model.setUserPhone(phone);
        User user = userMapper.selectOne(model);
        if (user == null){
            map.put("code",802);
            map.put("msg","手机号没注册");
            return map;
        }

        if (StringUtils.isBlank(user.getUserPwd())){
            map.put("code",812);
            map.put("msg","您未设置密码，请验证码登录后到个人中心设置密码。");
            return map;
        }

        //1.正常 2.拉黑
        if (user.getUserStatus()==2){
            map.put("code",811);
            map.put("msg","您的账号已被锁定");
            return map;
        }

        if (!user.getUserPwd().equals(pwd)){
            map.put("code",809);
            map.put("msg","密码有误");
            return map;
        }

        UserInfo info = new UserInfo();
        info.setUserId(user.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(info);
        map.put("user",user);
        map.put("userInfo",userInfo);

        return JsonData.success(map);
    }

    @Override
    public Map<String, Object> findPwd(String phone, String vcId, String codeNum, String pwd, String againPwd) {
        Map map = Maps.newHashMap();
        //判断验证码是否可用，正确
        Map map1 = codeService.checkVerificationCode(phone, vcId, codeNum);
        if ((Integer) map1.get("code") != Const.SUCCESS_CODE) {
            return map1;
        }

        //判断密码是否一致
        if (!pwd.equals(againPwd)){
            map.put("code",803);
            map.put("msg","两次密码输入不一致");
            return map;
        }

        User model = new User();
        model.setUserPhone(phone);
        User user = userMapper.selectOne(model);
        if (user == null){
            map.put("code",802);
            map.put("msg","手机号没注册");
            return map;
        }

        user.setUserPwd(pwd);
        userMapper.updateByPrimaryKeySelective(user);

        return JsonData.success(user);
    }

    @Override
    public Map<String, Object> registerByPhoneAndCode(String phone, String vcId, String codeNum, String pwd, String againPwd) {
        Map map = Maps.newHashMap();
        //判断验证码是否可用，正确
        Map map1 = codeService.checkVerificationCode(phone, vcId, codeNum);
        if ((Integer) map1.get("code") != Const.SUCCESS_CODE) {
            return map1;
        }

        if (!pwd.equals(againPwd)){
            map.put("code",803);
            map.put("msg","两次密码输入不一致");
            return map;
        }

        //判断手机号是否注册
        User user = new User();
        user.setUserPhone(phone);
        int i = userMapper.selectCount(user);
        if (i > 0){
            map.clear();
            map.put("code",801);
            map.put("msg","手机号已注册");
            return map;
        }

        String userId = AppUtil.uuid();
        user.setUserId(userId);

        user.setUserPwd(pwd);
        user.setUserType(1);
        user.setUserLoginName(phone);
        //默认手机号为昵称
        user.setUserNickName(phone);
        user.setUserStatus(1);
        user.setBalance(0.0);
        user.setUserToken(AppUtil.uuid());
        user.setCreateTime(new Date());

        UserInfo info = new UserInfo();
        info.setUserId(userId);
        info.setUiId(AppUtil.uuid());

        userMapper.insertSelective(user);
        userInfoMapper.insertSelective(info);

        map.put("user",user);
        map.put("userInfo",info);


        //将验证码修改为已使用状态
        SysVerificationCode code = new SysVerificationCode();
        code.setVcId(vcId);
        code.setVcStatus(2);
        codeMapper.updateByPrimaryKeySelective(code);

        return JsonData.success(map);
    }


    /**
     * @需求描述:辞退讲师业务逻辑层
     * @创建人:whh
     * @创建时间: 2019/11/18
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map dismissTeacher(String userId) {
        //将讲师的所有课程下架
        videosMapper.downVideoByUserId(userId);
        videosItemMapper.downVideoItemByUserId(userId);

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(userId);
        UserInfo userInfo =   userInfoMapper.selectOne(userInfoVo);
        if (userInfo!= null){
            //已经辞退过讲师
            if (userInfo.getIsTeacher() == 0){
                return JsonData.success(Const.OPREATE_MSG_SUCCESS);
            }
            //修改is_teacher = 0
            userInfo.setIsTeacher(0);
            Integer integer = userInfoMapper.updateByPrimaryKey(userInfo);
            if (integer >0 ){
                return JsonData.success(Const.OPREATE_MSG_SUCCESS);
            }
        }
        return JsonData.fail(Const.OPREATE_MSG_ERROR);
    }

    /**
     * @需求描述:指定讲师业务逻辑层
     * @创建人:whh
     * @创建时间: 2019/11/18
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    @Override
    public Map makeTeacher(String userId,String userDesc) {
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(userId);
        UserInfo userInfo =   userInfoMapper.selectOne(userInfoVo);
        //如果已经存在
        if (userInfo != null){
            //修改is_teacher = 2
            userInfo.setIsTeacher(2);
            userInfo.setUserDesc(userDesc);
            Integer integer = userInfoMapper.updateByPrimaryKey(userInfo);
            if (integer >0 ){
                return JsonData.success(Const.OPREATE_MSG_SUCCESS);
            }
        }

        userInfoVo.setIsTeacher(2);
        userInfoVo.setUserDesc(userDesc);
        Integer result = userInfoMapper.insertSelective(userInfoVo);
        if (result >0 ){
            return JsonData.success(Const.OPREATE_MSG_SUCCESS);
        }
        return JsonData.fail(Const.OPREATE_MSG_ERROR);
    }

    @Override
    public Map<String, Object> loginByCode(String phone, String vcId, String codeNum) {
        Map map = Maps.newHashMap();
        //判断验证码是否可用，正确
        Map map1 = codeService.checkVerificationCode(phone, vcId, codeNum);
        if ((Integer) map1.get("code") != Const.SUCCESS_CODE) {
            return map1;
        }

        User model = new User();
        model.setUserPhone(phone);
        User user = userMapper.selectOne(model);
        if (user!=null){
            //1.正常 2.拉黑
            if (user.getUserStatus()==2){
                map.put("code",811);
                map.put("msg","您的账号已被锁定");
                return map;
            }
            //登录成功，查询用户详情信息
            UserInfo info = new UserInfo();
            info.setUserId(user.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(info);
            map.put("user",user);
            map.put("userInfo",userInfo);
        }else{
            //没有注册，就直接注册
            user = new User();
            String userId = AppUtil.uuid();
            user.setUserId(userId);
            user.setUserPhone(phone);
            //默认密码
            user.setUserPwd("");
            user.setUserType(1);
            user.setUserLoginName(phone);
            //默认手机号为昵称
            user.setUserNickName(phone);
            user.setUserStatus(1);
            user.setBalance(0.0);
            user.setUserToken(AppUtil.uuid());
            user.setCreateTime(new Date());

            UserInfo info = new UserInfo();
            info.setUserId(userId);
            info.setUiId(AppUtil.uuid());

            userMapper.insertSelective(user);
            userInfoMapper.insertSelective(info);

            map.put("user",user);
            map.put("userInfo",info);
        }

        //将验证码修改为已使用状态
        SysVerificationCode code = new SysVerificationCode();
        code.setVcId(vcId);
        code.setVcStatus(2);
        codeMapper.updateByPrimaryKeySelective(code);

        return JsonData.success(map);
    }

    @Override
    public List<UserVo> findByWhere(UserVo user) {
        return userMapper.findByWhere(user);
    }


    @Override
    public Map<String, Object> phoneIsExist(String phone) {
        User model = new User();
        model.setUserPhone(phone);

        int flag = userMapper.selectCount(model);

        Map map = Maps.newHashMap();
        if (flag > 0){
            map.put("code",801);
            map.put("msg","手机号已注册");
        }else{
            map.put("code",200);
            map.put("msg","ok");
        }

        return map;
    }

    @Override
    public Map add(User user) {
        //判断是否存在该用户
        User user1 = new User();
        user1.setUserLoginName(user.getUserLoginName());
        //系统用户
        user1.setUserType(2);
        List<User> users = userMapper.select(user1);
        if (!users.isEmpty()){
            return JsonData.fail("Account already exists");
//            return JsonData.fail("账号已存在");
        }
        //1.注册用户 2.系统管理员
        user.setUserType(2);
        user.setCreateTime(new Date());
        user.setUserPwd(SecureUtil.md5(user.getUserPwd()));
        user.setUserId(SecureUtil.simpleUUID());
        //1.正常 2.拉黑
        user.setUserStatus(1);
        Integer integer = userMapper.insertSelective(user);
        return JsonData.returnMap(integer);
    }

    @Override
    public Map dels(String... userIds) {
        Integer integer=userMapper.dels(userIds);
        return JsonData.returnMap(integer);
    }
}
